package com.hphs.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hphs.info.ImgInfo;
import com.hphs.info.UploadInfo;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    //多文件上传
    //提取存储地址
    private static String filePath="D:/software/nginx-1.21.4/html/";
    //固定图片类型
    private static List<String> imgExts= CollUtil.newArrayList("jpg","png","jpeg","gif");

    @PostMapping
    public String upload(@RequestBody UploadInfo uploadInfo) throws InterruptedException {
        String name=uploadInfo.getName();
        String base64=uploadInfo.getBase64();
        System.out.println("name"+name);
        //截取base64的字节码 返回的结果是数组类型
        String[] base64s = StrUtil.splitToArray(base64, "base64,");
        //System.out.println("这是什么数据"+base64s[1]);
        byte[] bytes = Base64.decode(base64s[1]);
        //雪花id
        name= IdUtil.getSnowflakeNextIdStr()+"_"+name;
        //读取名字判断是什么类型
        String ext=FileUtil.getSuffix(name);
        String tempFolder="images/";
        if(!imgExts.contains(ext)){
            tempFolder=ext+"/";
        }
        // 把图片写入到nginx中
        FileUtil.writeBytes(bytes,filePath+tempFolder+name);

        //Thread.sleep(2000);
        return "http://www.hphs.com/"+tempFolder+name;
    }

    @GetMapping
    public List<ImgInfo> get(){
        //先获取指定目录下的文件
        List<String> fileNames =
                FileUtil.listFileNames("D:/software/nginx-1.21.4/html/images/");
        //stream中map元素转化方法
        // collect
        //遍历数据
        List<ImgInfo> collect=fileNames.stream().map(
                item-> {
            return new ImgInfo(item,"http://www.hphs.com/images/"+item);
        }).collect(Collectors.toList());

        return collect;

    }

}
